<template>
	<div>
		<el-table class="tableContent" row-key="id" border :data="list" style="width: 100%">
			<el-table-column label="ID" prop="id" width="70px" align="center" />
			<el-table-column label="用户名称" prop="username" width="120px" align="center" />
			<el-table-column label="真实姓名" prop="name" width="120px" align="center" />
			<el-table-column label="所属部门" prop="deptName" align="center" />
		</el-table>
	</div>
</template>


<script lang="ts">
	import {
		ref,
		toRefs,
		onMounted,
		reactive,
		defineComponent
	} from 'vue'
	// 拖拽插件
	import Sortable from 'sortablejs'
	export default defineComponent({
		setup() {
			const state = reactive({
				list: [{
						username: 1,
						id:1
					},
					{
						username: 2,
						id:2
					},
					{
						username: 3,
						id:3
					}
				],
			})
			
			// 创建拖拽实例
			const initSort = (className: string) => {
				const table = document.querySelector(`.${  className  } .el-table__body-wrapper tbody`);
			
				Sortable.create(table, {
					group: 'shared',
					animation: 150,
					easing: 'cubic-bezier(1, 0, 0, 1)',
					onStart: () => {
						// console.log("开始拖动");
					},
					// 结束拖动事件
					onEnd: ({
						newIndex,
						oldIndex
					}: any) => {
						// console.log(`拖动前索引${oldIndex}---拖动后索引${newIndex}`, "结束拖动");
						setNodeSort(state.list, oldIndex, newIndex)
					},
				})
			}
			// 拖拽完成修改数据排序
			const setNodeSort = (data: any, oldIndex: any, newIndex: any) => {
				const currRow = data.splice(oldIndex, 1)[0];
				data.splice(newIndex, 0, currRow);
			}
			onMounted(() => {
				initSort('tableContent')
			})
			return {
				...toRefs(state),
				onMounted,
				initSort,
				setNodeSort
			}
		}
	})
</script>
